<?php

namespace app\admin\service;

use app\admin\exception\AdminException;
use DI\Annotation\Inject;
use Webman\Http\UploadFile;

class Attachment
{
    /**
     * @var Auth
     * @Inject()
     */
    protected $auth = null;

    const SAVE_PATH = 'uploads';

    /**
     * @var UploadFile
     */
    protected $uploadFile = null;

    protected $sha1 = '';

    public function init(UploadFile $uploadFile) {
        $this->uploadFile = $uploadFile;
        $this->sha1 = '';
        return $this;
    }

    /**
     * @param UploadFile $uploadFile 文件对象
     * @return string
     */
    public function upload()
    {
        $this->checkFile();
        $model = \app\admin\model\Attachment::query()->where('sha1', $this->getSha1())->first();
        if (!$model) {
            $model = new \app\admin\model\Attachment();
            if ($this->auth && $this->auth->isLogin()) {
                $model->admin_id = $this->auth->getUserModel()->id;
            }
            $model->url = $this->saveFile();
            $model->filename = $this->uploadFile->getUploadName();
            $model->filesize = $this->uploadFile->getSize();
            $model->mimetype = $this->uploadFile->getUploadMineType();
            $model->storage = 'local';
            $model->sha1 = $this->getSha1();
            $model->save();
        }
        return $model->url;
    }

    protected function saveFile() {
        $filename =  $this->getSha1() . '.' . $this->uploadFile->getUploadExtension();
        $url =  $this->getSavePath() . $filename;
        $this->uploadFile->move(public_path() . $url);
        return $url;
    }

    protected function getSha1() {
        if (!$this->sha1) {
            $this->sha1 = sha1_file($this->uploadFile->getPathname());
        }
        return $this->sha1;
    }

    protected function getSavePath()
    {
        return DS . self::SAVE_PATH .DS . date("Y/m/d") . DS;
    }

    public function checkFile()
    {
        if (!$this->uploadFile || !$this->uploadFile->isValid()) {
            throw new AdminException($this->uploadFile ? '上传文件错误：' . $this->uploadFile->getUploadErrorCode() : '未接收到文件!');
        }
        $ext = $this->uploadFile->getUploadExtension();
        if (in_array($ext, ['php', 'html', 'htm'])) {
            throw new AdminException("文件不允许!");
        }
    }

    public function delete($url) {
        // 删除本地文件或云存储文件
        if (file_exists(public_path() . $url)) {
            unlink(public_path() . $url);
        }
    }
}
